<?php
/*
Plugin Name: WP GodModelAI Writer
Description: 天神大模型（chat.orderease.cn）驱动的WordPress文章写作助手
Version: 1.0.0
Author: 陈祖豪 Email：3469807212@qq.com
*/

if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('WP_AI_WRITER_VERSION', '1.0.0');
define('WP_AI_WRITER_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WP_AI_WRITER_PLUGIN_URL', plugin_dir_url(__FILE__));

// 加载核心类
require_once WP_AI_WRITER_PLUGIN_DIR . 'includes/class-ai-writer-api.php';

class WP_AI_Writer {
    private static $instance = null;
    private $api;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->api = new AI_Writer_API();
        add_action('init', array($this, 'init'));
        add_action('rest_api_init', array($this, 'register_rest_routes'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_block_editor_assets'));
    }

    public function init() {
        load_plugin_textdomain('wp-ai-writer', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }

    public function enqueue_block_editor_assets() {
        wp_enqueue_script(
            'wp-ai-writer-block',
            WP_AI_WRITER_PLUGIN_URL . 'js/block.js',
            array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-api-fetch'),
            WP_AI_WRITER_VERSION,
            true
        );

        wp_enqueue_style(
            'wp-ai-writer-style',
            WP_AI_WRITER_PLUGIN_URL . 'css/wp-ai-writer.css',
            array(),
            WP_AI_WRITER_VERSION
        );

        wp_localize_script('wp-ai-writer-block', 'wpAiWriter', array(
            'nonce' => wp_create_nonce('wp_rest'),
            'apiUrl' => rest_url('wp-ai-writer/v1')
        ));
    }

    public function register_rest_routes() {
        register_rest_route('wp-ai-writer/v1', '/generate', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_generate_request'),
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            }
        ));
    }

    public function handle_generate_request($request) {
        $params = $request->get_params();
        $prompt = sanitize_textarea_field($params['prompt']);
        
        if (empty($prompt)) {
            return new WP_Error('empty_prompt', '提示词不能为空', array('status' => 400));
        }

        $result = $this->api->generate_content($prompt);
        
        if (!$result['success']) {
            return new WP_Error('generation_failed', $result['message'], array('status' => 500));
        }

        return rest_ensure_response(array(
            'success' => true,
            'content' => $result['content']
        ));
    }
}

// 初始化插件
function wp_ai_writer() {
    return WP_AI_Writer::get_instance();
}

wp_ai_writer(); 